<?php

namespace app\task\model;

use app\pilot\model\PilotModel;
use think\admin\Model;


/**
 * 订单接单模型
 * @class OrderModel
 * @package app\task\model
 */
class OrderModel extends Model
{
    protected $name = 'task_order';

    /**
     * 字典-状态类型
     */
    public const STATUS__PENDING_COMPLETION = 0;
    public const STATUS__PENDING_REVIEW = 1;
    public const STATUS__COMPLETED = 2;
    public const STATUS__REVIEW_FAILED = 3;
    public const STATUS__APPLYING = 4;
    public const STATUS__STANDBY = 5;
    public const STATUS__APPLY_FAILED = 6;
    public const STATUS__CANCELED = -1;
    public const STATUS_DICT = [
        self::STATUS__APPLYING => '申请中',
        self::STATUS__STANDBY => '候补中',
        self::STATUS__APPLY_FAILED => '申请失败',
        self::STATUS__PENDING_COMPLETION => '待完成',
        self::STATUS__PENDING_REVIEW => '待审核',
        self::STATUS__COMPLETED => '已完成',
        self::STATUS__REVIEW_FAILED => '审核不通过',
        self::STATUS__CANCELED => '已取消',
    ];

    /**
     * 状态获取器
     * @param $value
     * @param $data
     * @return string
     */
    public function getStatusTextAttr($value, $data)
    {
        return self::STATUS_DICT[$data['status']] ?? '';
    }

    /**
     * 生成唯一的订单号
     * @return string
     */
    public static function createOrderNum()
    {
        $newOrderNo = date('YmdHis') . rand(100000, 999999);
        if ((new self())->where('order_no', $newOrderNo)->count() > 0) {
            return self::createOrderNum();
        }
        return $newOrderNo;
    }

    /**
     * 关联任务订单表
     */
    public function task(){
        return $this->belongsTo(TaskModel::class, 'task_id', 'id');
    }

    /**
     * 关联任务飞手
     */
    public function pilot(){
        return $this->belongsTo(PilotModel::class, 'pilot_id', 'id');
    }
}
